/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include "Server.h"

using namespace std;

void server_error(const char *msg)
{
    perror(msg);
    exit(1);
}



int main(int argc, char *argv[])
{
     int portno, sockfd, newsockfd;
     socklen_t clilen;
     struct sockaddr_in serv_addr, cli_addr;

     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }

	 //Get the socket
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        server_error("ERROR opening socket");

     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);

	 //Set ther server address parameters
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);

	 //Bind to the socket
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
		server_error("ERROR on binding");

	//Listen for the client to connect

	while(true){
		listen(sockfd,5);

		//Establish the connection
		clilen = sizeof(cli_addr);
		newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);

		if (newsockfd < 0) {
			 server_error("ERROR on accept");
			 return 0;
		}

		pid_t pid = fork();
		if(pid == 0) { //Child
			close(sockfd);

			Server server(newsockfd);
			server.run();

			close(newsockfd);
			exit(0);
		}

		close(newsockfd);

	}

	//Need a way to gracefully exit

	/*
	while(true){
		int status;
		pid_t done = wait(&status);
		if (done == -1) {
			if (errno == ECHILD) break; // no more child processes
		} else {
			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
				cerr << "pid " << done << " failed" << endl;
			exit(1);
			}
		}
	}
	*/
	
	

	close(sockfd);
    return 0; 
}
